package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.hmdp.entity.User;
import com.hmdp.properties.JwtProperties;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Jwt 工具类
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtUtils {

    private final JwtProperties jwtProperties ;

    /**
     * 生成 jwt 令牌
     * @param user
     * @return
     */
    public String generateJwt(User user) {
        log.info("开始生成 jwt 令牌 ... 用户：{}",user);
        Map<String, Object> chaims = BeanUtil.beanToMap(user,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtProperties.getSignKey())
                .addClaims(chaims)
                .setExpiration(new Date(System.currentTimeMillis() + jwtProperties.getExpire()))
                .compact();
        return jwt ;
    }

}
